<template>
  <div class="news-detail">
    <div class="container">
      <div class="back-link">
        <router-link to="/news" class="back-btn">« 返回新闻列表</router-link>
      </div>
      
      <div class="detail-header">
        <div v-if="!isEditing">
          <h1 class="detail-title">{{ newsItem ? newsItem.title : '加载中...' }}</h1>
          <div class="detail-meta">
            <span class="date">发布时间: {{ newsItem ? formatDate(newsItem.releaseTime || newsItem.date) : '加载中...' }}</span>
            <span class="author">来源: 代码小英雄</span>
          </div>
        </div>
        <div v-else class="edit-mode">
          <div class="form-group">
            <label for="edit-title">新闻标题</label>
            <input type="text" id="edit-title" v-model="editableNews.title" class="edit-title" placeholder="请输入新闻标题">
          </div>
           <div class="form-group">
             <label for="edit-time">发布时间</label>
             <input type="text" id="edit-time" v-model="editableNews.releaseTime" class="edit-time" placeholder="格式: 2025-10-13 10:00:00">
             <small class="form-hint">请输入发布时间，格式: YYYY-MM-DD HH:mm:ss</small>
           </div>
        </div>
      </div>
      
      <div class="detail-actions" v-if="!isEditing">
        <button @click="startEditing" class="btn btn-edit">编辑内容</button>
      </div>
      
      <div class="detail-content">
        <div v-if="loading" class="loading">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
        <div v-else-if="newsItem">
          <div v-if="!isEditing">
            <div class="content-text" v-html="formatContent(newsItem.content)"></div>
          </div>
          <div v-else class="edit-content-section">
            <div class="form-group">
              <label for="edit-content">新闻内容</label>
              <textarea id="edit-content" v-model="editableNews.content" class="edit-content" rows="15" placeholder="请输入新闻内容"></textarea>
              <small class="form-hint">支持换行，发布后会自动格式化</small>
            </div>
            <div class="edit-actions">
              <button @click="saveChanges" class="btn btn-save">保存修改</button>
              <button @click="cancelEditing" class="btn btn-cancel">取消编辑</button>
            </div>
          </div>
        </div>
        <div v-else class="error">
          <p>新闻详情加载失败，请重试。</p>
          <button @click="loadNewsDetail" class="btn btn-retry">重新加载</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { newsApi } from '@/api/news'
import logger from '../utils/logger.js'

export default {
  name: 'NewsDetail',
  data() {
    return {
      newsItem: null,
      loading: false,
      isEditing: false,
      editableNews: {
        id: null,
        title: '',
        releaseTime: '',
        content: ''
      }
    };
  },
  mounted() {
    // 获取路由参数中的新闻ID并加载新闻详情
    this.loadNewsDetail();
  },
  methods: {
    // 加载新闻详情
    async loadNewsDetail() {
      const newsId = this.$route.params.id;
      if (!newsId) {
        this.$router.push('/news');
        return;
      }
      
      this.loading = true;
      
      try {
        logger.log('📰 [NewsDetail] 开始获取新闻详情，ID:', newsId);
        
        const response = await newsApi.getNewsDetail(newsId);
        
        logger.log('📰 [NewsDetail] API响应:', response);
        
        // 处理API返回的数据
        if (response && response.data) {
          this.newsItem = response.data;
        } else if (response) {
          // 如果直接返回新闻对象
          this.newsItem = response;
        } else {
          throw new Error('未找到新闻详情');
        }
        
        logger.log('📰 [NewsDetail] 新闻详情加载成功:', this.newsItem);
        
      } catch (error) {
        logger.error('📰 [NewsDetail] 获取新闻详情失败:', error);
        
        // 显示错误消息
        const errorMessage = error.response?.data?.message || error.message || '获取新闻详情失败';
        if (this.$message) {
          this.$message.error(errorMessage);
        } else {
          console.error('获取新闻详情失败:', errorMessage);
        }
        
        this.newsItem = null;
      } finally {
        this.loading = false;
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      
      try {
        // 如果是 "YYYY-MM-DD HH:mm:ss" 格式，转换为更友好的格式
        if (dateString.includes(' ')) {
          const date = new Date(dateString);
          if (isNaN(date.getTime())) {
            return dateString; // 如果日期无效，返回原字符串
          }
          
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          
          return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 如果已经是其他格式，直接返回
        return dateString;
      } catch (error) {
        logger.error('日期格式化失败:', error);
        return dateString;
      }
    },
    
    // 格式化内容，将换行符转换为HTML
    formatContent(content) {
      if (!content) return '';
      
      return content
        .replace(/\n/g, '<br>')
        .replace(/\r/g, '');
     },
    
     startEditing() {
       // 复制当前新闻数据到可编辑的对象中
       this.editableNews = {
         id: this.newsItem.id,
         title: this.newsItem.title,
         releaseTime: this.newsItem.releaseTime || '',
         content: this.newsItem.content
       };
       this.isEditing = true;
     },
    
     async saveChanges() {
       // 数据验证
       if (!this.editableNews.title.trim()) {
         if (this.$message) {
           this.$message.error('请输入新闻标题');
         } else {
           alert('请输入新闻标题');
         }
         return;
       }
       if (!this.editableNews.releaseTime.trim()) {
         if (this.$message) {
           this.$message.error('请输入发布时间');
         } else {
           alert('请输入发布时间');
         }
         return;
       }
       
       // 验证时间格式
       const timePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
       if (!timePattern.test(this.editableNews.releaseTime.trim())) {
         if (this.$message) {
           this.$message.error('时间格式不正确，请使用格式: YYYY-MM-DD HH:mm:ss');
         } else {
           alert('时间格式不正确，请使用格式: YYYY-MM-DD HH:mm:ss');
         }
         return;
       }
       
       if (!this.editableNews.content.trim()) {
         if (this.$message) {
           this.$message.error('请输入新闻内容');
         } else {
           alert('请输入新闻内容');
         }
         return;
       }
       
       try {
         logger.log('📝 [NewsDetail] 开始更新新闻，ID:', this.editableNews.id);
         
         // 准备API请求数据
         const updateData = {
           Id: this.editableNews.id,  // 注意这里是大写的 Id
           title: this.editableNews.title.trim(),
           content: this.editableNews.content.trim(),
           releaseTime: this.editableNews.releaseTime.trim()
         };
         
         console.log('发送更新新闻请求:', updateData);
         
         // 调用更新新闻API
         const response = await newsApi.updateNews(updateData);
         
         console.log('更新新闻成功:', response);
         
         // 更新本地数据
         this.newsItem = { 
           ...this.newsItem,
           ...updateData
         };
         
         // 退出编辑模式
         this.isEditing = false;
         
         // 移除成功提示弹窗，改善用户体验
         // if (this.$message) {
         //   this.$message.success('新闻修改成功！');
         // } else {
         //   alert('新闻修改成功！');
         // }
         
         logger.log('📝 [NewsDetail] 新闻更新成功');
         
       } catch (error) {
         logger.error('📝 [NewsDetail] 更新新闻失败:', error);
         
         const errorMessage = error.response?.data?.message || error.message || '保存失败，请重试';
         if (this.$message) {
           this.$message.error(errorMessage);
         } else {
           alert(errorMessage);
         }
       }
     },
    cancelEditing() {
      // 取消编辑，恢复原数据
      this.isEditing = false;
      this.editableNews = {
        id: null,
        title: '',
        releaseTime: '',
        content: ''
      };
    }
  }
};
</script>

<style scoped>
.news-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 30px;
}

.back-link {
  margin-bottom: 20px;
}

.back-btn {
  color: #3e8ef7;
  text-decoration: none;
  font-size: 14px;
}

.back-btn:hover {
  text-decoration: underline;
}

.detail-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.detail-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 15px;
}

.detail-meta {
  color: #999;
  font-size: 14px;
}

.detail-meta .date {
  margin-right: 20px;
}

.detail-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
  transition: background-color 0.3s;
}

.btn-edit {
  background-color: #3e8ef7;
  color: white;
}

.btn-edit:hover {
  background-color: #2c7be5;
}

.btn-save {
  background-color: #4CAF50;
  color: white;
}

.btn-save:hover {
  background-color: #43A047;
}

.btn-cancel {
  background-color: #f44336;
  color: white;
}

.btn-cancel:hover {
  background-color: #e53935;
}

/* 编辑模式样式 */
.edit-mode {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 2px dashed #dee2e6;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-weight: 600;
  color: #495057;
  margin-bottom: 8px;
  font-size: 14px;
}

.form-hint {
  display: block;
  color: #6c757d;
  font-size: 12px;
  margin-top: 5px;
  font-style: italic;
}

.edit-title {
  width: 100%;
  font-size: 18px;
  padding: 12px 16px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  transition: border-color 0.3s, box-shadow 0.3s;
  background-color: #fff;
}

.edit-title:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
  outline: none;
}

.edit-time {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  transition: border-color 0.3s, box-shadow 0.3s;
  background-color: #fff;
  font-size: 14px;
}

.edit-time:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
  outline: none;
}

.edit-content-section {
  margin-top: 20px;
}

.edit-content {
  width: 100%;
  padding: 12px 16px;
  font-size: 14px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  resize: vertical;
  min-height: 200px;
  transition: border-color 0.3s, box-shadow 0.3s;
  background-color: #fff;
  font-family: inherit;
  line-height: 1.5;
}

.edit-content:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
  outline: none;
}

.edit-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #dee2e6;
}

.edit-actions .btn {
  min-width: 100px;
  font-weight: 500;
}

.detail-content {
  line-height: 1.8;
  color: #333;
  font-size: 16px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error {
  text-align: center;
  padding: 40px;
  color: #f44336;
}

.btn-retry {
  background-color: #2196F3;
  color: white;
  margin-top: 10px;
}

.btn-retry:hover {
  background-color: #1976D2;
}

.content-text {
  line-height: 1.8;
  color: #333;
  font-size: 16px;
}

@media (max-width: 768px) {
  .container {
    padding: 15px;
  }
  
  .detail-title {
    font-size: 20px;
  }
  
  .detail-content {
    font-size: 14px;
  }
  
  .edit-title {
    font-size: 20px;
  }
  
  .edit-content {
    font-size: 14px;
  }
}
</style> 